﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace FourKill.Engine
{
    public class PathPersonObject : BaseGameObject, IMovementObservable, IPath
    {
        private Sprite _sprite;
        public event EventHandler<MovementArgs> Moved;
        private Coordinates3D _currentPointOnPath;
        private List<Coordinates3D> _expandedPointsPath = new List<Coordinates3D>();
        private double _movementDistance = 1;
        private int _pointIndex = 0;

        public PathPersonObject(List<Coordinates3D> path)
        {
            if (path.Count() > 0)
            {
                Path = path;
                _expandedPointsPath = Path.ExpandPath(_movementDistance);
                _currentPointOnPath = Path.First();
            }
        }

        public override void Tick()
        {
            // Determine if any points are left to be navigated.
            if (_expandedPointsPath.Count() - 1 > _pointIndex + 1)
            {
                _pointIndex++;

                // Calculate bearing to new point.  This is on a 2d plane.
                double angle = _currentPointOnPath.AngleToPoint(_expandedPointsPath[_pointIndex]);

                if (angle != Bearing)
                {
                    this.Bearing = angle;
                }

                this.Move(_movementDistance);
                _currentPointOnPath = _expandedPointsPath[_pointIndex];
            }
            else
            {
                // TODO: Reverse or reset.
                _pointIndex = 0;
            }

            var placement = new Placement
            {
                X = this.X,
                Y = this.Y,
                Z = this.Z,
                Bearing = this.Bearing,
                TotalMovement = this.TotalMovement
            };

            if (Moved != null)
            {
                Moved(this, new MovementArgs { Placement = placement });
            }
        }

        public Sprite Sprite
        {
            get
            {
                _sprite = _sprite ?? Sprite.Instance(SpriteSheets.GetRandomCreatureSpriteSheet());
                return _sprite;
            }
        }

        public override IPaintable Painter
        {
            get
            {
                return Sprite;
            }
        }
    }
}
